package mySeleniumDriver;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import jxl.read.biff.BiffException;

import org.openqa.selenium.Alert;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class KeywordRelatedFunctions extends BaseClass {

  DateTimeFunctions dtfObj = new DateTimeFunctions();
  DataTable dtObj = new DataTable();

  public void waitForPageToLoad(Integer timeoutinsecs) {
    ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
      public Boolean apply(WebDriver driver) {
        return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals(
            "complete");
      }
    };
    WebDriverWait wait = new WebDriverWait(D8, timeoutinsecs);
    wait.until(pageLoadCondition);
  }

  public String getcCellData() throws BiffException, IOException {

    String textToReturn = "";

    if (cCellData.trim().substring(0, 1).equalsIgnoreCase("#")) {
      textToReturn = map.get(cCellData.trim().substring(1, (cCellData.trim().length())));

    } else if (cCellData.trim().startsWith("dt_")) {

      textToReturn = dtObj.getDataTableValue(cCellData.trim(), dtrownum);
      iflag = 1;
      /*
       * String ObjectSetValtableheader[] = cCellData.trim().split("_"); int column = 0; String
       * Searchtext = ObjectSetValtableheader[1]; for (column = 0; column < DTcolumncount; column++)
       * { if (Searchtext.equalsIgnoreCase(DTsheet .getCell(column, 0).getContents()) == true) {
       * textToReturn = DTsheet.getCell(column, dtrownum).getContents(); iflag = 1; }
       * 
       * }
       */

    } else if (cCellData.trim().startsWith("$")) {

      textToReturn = dtfObj.getSystemVariable(cCellData.trim());

    } else if (cCellData.trim().startsWith("db_")) {

      textToReturn = DBResultSet2D.get(cCellData.trim().substring(3, (cCellData.trim().length())));

    }

    else {
      textToReturn = cCellData.trim();
    }

    return textToReturn;
  }


  public boolean isModalDialogShowing() throws Exception {


    for (int i = 0; i < 5; i++) {
      try {
        Set<String> dialogs = D8.getWindowHandles();
        log("info", "Trying to detect AUTH dialog[iteration-" + i + "].Window handlers size- "
            + dialogs.size());
        Alert auth_alert = D8.switchTo().alert();
        log("info", "AUTH dialog Found with text: " + auth_alert.getText());
        return true;
      } catch (Exception e) {
        if (e.getMessage().contains("Modal dialog present")) {
          log("info", "AUTH Dialog Found." + e.getMessage().substring(0, 35));
          return true;
        }
        // Alert not found try next iteration
        log("error", "Exception caught while checking for AUTH dialog: "
            + e.getMessage().substring(0, 35));
        Thread.sleep(1000);
      }

    }

    return false;
  }



  public int getEndLoopRowNo(int startSearchFrom) {
    int endLoopRowNo = startSearchFrom;
    for (int s = startSearchFrom; s < TScrowcount; s++) {
      // System.out.println("DEBUG:Checking for endloop keyword @ row :" + s + " with value:" +
      // TScsheet.getCell(1,s).getContents());
      if ((TScsheet.getCell(1, s).getContents()).equalsIgnoreCase("endloop")
          && (TScsheet.getCell(0, s).getContents()).equalsIgnoreCase("r")) {
        log("info", "Endloop keyword found @ row :" + s);
        endLoopRowNo = s - 1;
        break;
      }
    }
    return endLoopRowNo;

  }


  public boolean isFolderUpdateComplete(String foldername, int timeoutinsecs) throws Exception {

    Thread.sleep(5000);
    Map<String, String> sizeBeforeSleep = new HashMap<String, String>();
    Map<String, String> sizeAfterSleep = new HashMap<String, String>();

    for (int i = 0; i < timeoutinsecs; i++) {
      log("info", "checking download completion status in iteration:" + (i + 1));
      File dir = new File(foldername);

      try {
        sizeBeforeSleep.clear();
        for (File file : dir.listFiles()) {
          sizeBeforeSleep.put(file.getName(), "Size:" + file.length());
        }
        Thread.sleep(15000);
        sizeAfterSleep.clear();
        for (File file : dir.listFiles()) {
          sizeAfterSleep.put(file.getName(), "Size:" + file.length());
        }

        boolean isDownloadInProgress = false;

        for (String key : sizeBeforeSleep.keySet()) {

          if (sizeBeforeSleep.get(key).equalsIgnoreCase(sizeAfterSleep.get(key))) {
            // do nothing
          } else {
            log("info", "File[" + key + "] is being updated....Retrying after a sec");
            isDownloadInProgress = true;
          }
        }

        if (isDownloadInProgress) {
          // log("info","File is being updated....Retrying after a sec");

        } else {
          log("info", "File downloaded successfully within the specified time.");
          return true;
        }


      } catch (Exception e) {
        log("error", "Exception caught in  isFolderUpdateComplete function.(" + e.getMessage()
            + ")");
      }
    }
    log("error",
        "File download is NOT complete within specified time.Please increase the timeout in test script.");
    return false;
  }

  /*
   * public long getLastModifiedTime(String filename) { long lastModifiedTime; File f = new
   * File(filename); lastModifiedTime = f.lastModified(); return lastModifiedTime; }
   */

  public boolean isCompletelyDownloaded(String filename, int timeoutinsecs)
      throws InterruptedException {
    Thread.sleep(7000);
    File file = new File(filename + ".part");
    for (int i = 0; i < timeoutinsecs; i++) {
      Thread.sleep(1000);
      try {
        log("info", "Checking if the file exists:" + file.getAbsolutePath());
        if (file.exists()) {
          log("info", "File is being updated....Retrying after a sec");
        } else {
          log("info", "File downloaded successfully within the specified time.");
          return true;
        }
      } catch (Exception e) {
        log("error", "Exception occured while checking part file existence:" + e.getMessage());
      }
    }

    log("error",
        "File download is NOT complete within specified time.Please increase the timeout in test script.");
    return false;

  }

}
